/* ==============================================================================
*
*   Copyright (c) 2010, Pierre Favier
*   All rights reserved.
*
*   NTasking is free software: you can redistribute it and/or modify it
*   under the terms of the GNU General Public License as published by the
*   Free Software Foundation.
*
*   Redistribution and use in source and binary forms, with or without
*   modification, are permitted provided that the following conditions
*   are met:
*
*   -   Redistributions of source code must retain the above copyright notice,
*       this list of conditions and the following disclaimer.
*
*   -   Redistributions in binary form must reproduce the above
*       copyright notice, this list of conditions and the following
*       disclaimer in the documentation and/or other materials
*       provided with the distribution.
*
*   THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
*   WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
*   OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
*   DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
*   BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
*   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
*   TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
*   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
*   ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
*   TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
*   THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
*   SUCH DAMAGE.
*
* ============================================================================== */

using System;

namespace NTasking.Internals
{

    /// <summary>
    /// Represent the base of all entry families with a given method profile (i.e. parameters and return type) 
    /// </summary>
    /// <typeparam name="IndexT">The type of the index of the method family.</typeparam>
    /// <typeparam name="RetT">The return type of the entry family</typeparam>
    /// <typeparam name="CallDelegateT">A delegate type representing the calling profile for performing a direct call.</typeparam>
    /// <typeparam name="SCallDelegateT">A delegate type representing the calling profile for performing a selective call.</typeparam>
    /// <typeparam name="ACallDelegateT">A delegate type representing the calling profile for performing an asynchronous call.</typeparam>
    /// <typeparam name="ExecuteDelegateT">A delegate type representing the calling profile for executing a call.</typeparam>
    public abstract class MethodFamily<IndexT, RetT, CallDelegateT, SCallDelegateT, ACallDelegateT, ExecuteDelegateT> :
        SynchronizedMethod<RetT, CallDelegateT, SCallDelegateT, ACallDelegateT, ExecuteDelegateT>,
        IIndexed<IndexT>

        where CallDelegateT : class // Should be MulticastDelegate but refused by the compiler
        where SCallDelegateT : class // Should be MulticastDelegate but refused by the compiler
        where ACallDelegateT : class // Should be MulticastDelegate but refused by the compiler
        where ExecuteDelegateT : class // Should be MulticastDelegate but refused by the compiler
    {

        private IndexT _index;




        /// <summary>
        /// Gets or sets a value indicating whether the index of the current instance has been set.
        /// </summary>
        /// <value><c>true</c> if the index of the current instance has been set; otherwise, <c>false</c>.</value>
        internal bool IndexSet { get; private set; }


        /// <summary>
        /// Gets or sets a delegate used to determine if a given index value is valid.
        /// </summary>
        /// <value>A delegate used to determine if a given index value is valid.</value>
        public Func<IndexT, bool> IndexValidator { get; set; }


        /// <summary>
        /// Initializes a new instance of the <see cref="MethodFamily{IndexT,RetT,CallDelegateT,SCallDelegateT,ExecuteDelegateT,MemberT}"/> class.
        /// </summary>
        internal MethodFamily()
        {
            IsEntry = true;
        }


        /// <summary>
        /// Gets a delegate used to call the specified member of this method family.
        /// </summary>
        /// <value>A delegate used to call the specified member of this method family</value>
        public CallDelegateT this[IndexT index]
        {
            get
            {
                if (!IndexIsValid(index))
                    throw Errors.MemberIndexOutOfRange(this, index);

                return CreateMemberDelegate(index);
            }
        }


        protected abstract CallDelegateT CreateMemberDelegate(IndexT index);


        /// <summary>
        /// Create an <see cref="MethodAccept"/> representing an accept of the current instance.
        /// </summary>
        /// <value>An <see cref="MethodAccept"/> representing an accept of the current instance.</value>
        internal override MethodAccept CreateAccept()
        {
            var result = new MethodAccept<IndexT, ExecuteDelegateT> { Target = Family };

            if (IndexSet)
                result.Index = Index;

            return result;
        }


        /// <summary>
        /// Determines whether this instance is equeal to the specified <see cref="SynchronizedMethod"/>.
        /// </summary>
        /// <param name="other">The other <see cref="SynchronizedMethod"/>.</param>
        /// <returns>
        /// 	<c>true</c> if this instance is equal to the specified <see cref="SynchronizedMethod"/>; otherwise, <c>false</c>.
        /// </returns>
        internal override bool IsEqual(SynchronizedMethod other)
        {
            return other.Family == Family && ((IIndexed<IndexT>)other).Index.Equals(Index);
        }


        /// <summary>
        /// Create a <see cref="MethodCall"/> representing a call of the current instance
        /// </summary>
        /// <returns>
        /// A <see cref="MethodCall"/> representing a call of the current instance
        /// </returns>
        internal override MethodCall CreateCall()
        {
            return CreateCall(null);
        }


        /// <summary>
        /// Create a <see cref="MethodCall"/> representing a call of the current instance with the specified parameters
        /// </summary>
        /// <returns>
        /// A <see cref="MethodCall"/> representing a call of the current instance
        /// </returns>
        internal MethodCall<IndexT, RetT> CreateCall(CallContext<RetT> context)
        {
            return new MethodCall<IndexT, RetT>(this, context, Index);
        }


        /// <summary>
        /// Check if a given index is valid.
        /// </summary>
        /// <param name="index">The index to be checked.</param>
        /// <returns><c>true</c> if the index is valid; <c>false</c> otherwise</returns>
        private bool IndexIsValid(IndexT index)
        {
            return IndexValidator == null || IndexValidator(index);
        }


        /// <summary>
        /// Retrieve a <see cref="T:System.String"/> which represents this instance's Index if any.
        /// </summary>
        /// <returns>
        /// A <see cref="T:System.String"/> which represents this instance's Index if any; otherwise an empty string.
        /// </returns>
        internal override string IndexRepresentation()
        {
            if (!IndexSet)
                return "[" + typeof(IndexT) + "]";

            // To avoid infinite recursion in case an MethodFamily is indexed by MethodCall, replace the index by the Thread
            // from which the MethocCall was executed

            // ReSharper disable PossibleNullReferenceException
            return "[" + (Index is MethodCall ? (Index as MethodCall).Thread.ToString() : Index.ToString()) + "]";
            // ReSharper restore PossibleNullReferenceException
        }


        IndexT IIndexed<IndexT>.Index
        {
            get
            {
                return Index;
            }
            set
            {
                Index = value;
            }
        }


        /// <summary>
        /// Gets or sets a value representing the index associated with the current instance.
        /// </summary>
        /// <value>The index associated with the current instance.</value>
        internal IndexT Index
        {
            get { return _index; }
            set
            {
                _index = value;
                IndexSet = true;
            }
        }

    }

}
